from django.shortcuts import render
from rest_framework.filters import OrderingFilter
from rest_framework.response import Response
from rest_framework.views import APIView
import logging
from rest_framework.generics import ListAPIView
from rest_framework.viewsets import ReadOnlyModelViewSet

from news.models import News, NewsCategory, NewsComments
from news.serializers import NewsListSerializer, NewsSerializer, NewsCategorySerializer, \
    UserTopNewsSerializer, NewsCommentsSerializer
from users.models import User

logger = logging.getLogger('django')

# 首页部分


class NewsCategoryView(ListAPIView):
    """
    新闻分类视图
    """
    serializer_class = NewsCategorySerializer

    def get_queryset(self):
        return NewsCategory.objects.all()


class NewsListView(ListAPIView):
    """
    该新闻分类的新闻列表
    """
    serializer_class = NewsListSerializer
    # 通过category_id返回给前端新闻对象
    filter_backends = (OrderingFilter,)
    ordering_fileds = ('create_time',)

    def get_queryset(self):
        category_id = self.kwargs['category_id']
        return News.objects.filter(category_id=category_id).order_by('-create_time')


# 新闻详情部分

class NewsView(APIView):
    """
    单条新闻
    """

    def get(self, request, news_id):
        news_id = self.kwargs['news_id']
        # news_id = request.GET.get('news_id')
        news = News.objects.get(id=news_id)
        serializer = NewsSerializer(news)
        return Response(serializer.data)


class NewsCommentsView(APIView):
    """
    评论视图
    """
    serializer_class = NewsCommentsSerializer

    def get(self, request, news_id):
        news_id = self.kwargs['news_id']
        # news_id = request.GET.get('news_id')
        news = News.objects.get(id=news_id)
        comments = NewsComments.objects.filter(news=news)
        serializer = NewsCommentsSerializer(comments, many=True)
        return Response(serializer.data)


class UserTopNewsView(ListAPIView):
    """
    头条详情页作者相关文章展示(返回作者阅读量最高的4条)
    """
    serializer_class = UserTopNewsSerializer

    def get_queryset(self):
        news_id = self.kwargs['news_id']
        news = News.objects.get(id=news_id)
        return News.objects.filter(user=User.objects.get(id=news.user_id)).order_by('-clicks')[0:4]


class TopNewsView(ListAPIView):
    """
    详情页相关文章展示(返回阅读量最高的4条)
    """
    serializer_class = NewsListSerializer

    def get_queryset(self):
        return News.objects.all().order_by('-clicks')[0:4]


